﻿
using System;
using System.Collections.Generic;
using MiniWeb.Core.Dtos;
using MiniWeb.Core.Entities;
using MiniWeb.Dao;
using MiniWeb.Core.Entities;
using WFramework.MvcPager;

namespace MiniWeb.Task
{
    public class ShopCartTask
    {
        private readonly ShopCartDao _dao = new ShopCartDao();
        private readonly ProductsInfoDao _productsInfoDao = new ProductsInfoDao();
        
        public PagedList<ShopCart> GetPagedList(int pageIndex, int pageSize)
        {
            return _dao.GetPagedList(pageIndex, pageSize);
        }

        public ShopCart GetById(int id)
        {
            return _dao.GetById(id);
        }
        public void Delete(string account, int pid)
        {
            _dao.Delete(account, pid);
        }

       

        public bool Exists(int id)
        {

            return _dao.Exists(id);
        }

        public void Add(ShopCart model)
        {

            _dao.Add(model);
        }

        public void DeleteCartByAccount(string account)
        {
            _dao.DeleteCartByAccount(account);
        }

        public void Update(ShopCart model)
        {

            _dao.Update(model);
        }

        public List<ShopCart> GetAll(int? top, string strwhere, string orderby)
        {
            return _dao.GetAll(top, strwhere, orderby);
        }

        public decimal GetTotalRMB(string account)
        {
            return _dao.GetTotalRMB(account);
        }

        public List<ShopCartProductInfo> GetCartList(string account)
        {
            return _dao.GetCartList(account);
        }

        public bool IsSame(string account, int pid, out int opid)
        {
            return _dao.IsSame(account, pid, out opid);
        }

        public bool AddCart(string account, int pid,int num,out string msg)
        {
            msg = string.Empty;
           

            int opid = 0;
           

            if(_dao.IsSame(account,pid ,out opid))
            {
                var model = _dao.GetById(opid);
                model.Num += num;
                _dao.Update(model);
            }
            else
            {
                var promodel = _productsInfoDao.GetSellById(pid);
              
                if(promodel==null)
                {
                    return false;
                }

                _dao.Add(new ShopCart
                             {
                                 Num = 1,
                                 Account = account,
                                 ProductID = promodel.ID,
                                 CreateDate = DateTime.Now,

                                
                             });
            }
            return true;
        }
    }
}